<?php

namespace App\Http\Controllers\Api;

use App\Libs\WeChat\WxSmallClient;
use App\Models\member;
use App\Models\member_bonus_record;
use App\Models\order_info;
use App\Models\sign_record;
use App\Models\user;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Redis;

class MemberController extends Controller
{
    const status = ["NORMAL",// 正常
                    "EXPIRE", //已过期
                    "GIFTING",//转赠中   DELETE 已删除，UNAVAILABLE 已失效];
                    "GIFT_SUCC",// 转赠成功
                    "GIFT_TIMEOUT",//转赠超时
                    "DELETE",//已删除
                    "UNAVAILABLE"//已失效
    ];

    const LEVEL_MAN = ['小主',// 正常
        "小王子",
        "伯爵",
        "陛下",
    ];

    const LEVEL= ['环保新秀',// 正常
        "环保少侠",
        "环保大侠",
        "环保掌门",
        "环保宗师",
        "环保盟主",
    ];

    const LEVEL_WOMAN= ['小主',// 正常
        "小公主", //已过期//小公主/小王子  //王妃/伯爵 女王/陛下
        "王妃",
        "女王",
    ];

    /**
     *获取会员信息
     */
    public function getMember(Request $request){
        $openid = $request->openid;
        $member_info = get_member(['openid'=>$openid]);
        //$member_info = member::where(['openid'=>$openid])->first();
        //type 1.需要领卡 2.更新不需要领卡
        if($member_info){
            $type = 2;
            $res = WxSmallClient::getMember($member_info['code']);
            $arr['nickname'] = $res->nickname;
            $arr['membership_number'] = $res->membership_number;
            $arr['bonus'] = $res->bonus;
            $arr['sex'] = $res->sex=='MALE'?1:0;
            $arr['user_card_status'] = array_search($res->user_card_status,self::status);
            //计算消费积分
            $consumer_total = $this->getbonus(['openid'=>$openid,'species'=>1,'type'=>1]);
            //计算总积分
            $total = $this->getbonus(['openid'=>$openid,'type'=>1]);
            $level = get_level($total,$consumer_total);
            //$arr['level'] = $member_info['gender']==1?self::LEVEL_MAN[$level]:self::LEVEL_WOMAN[$level];
            $arr['level'] = $level;
            $arr['crown_num'] = intval($res->bonus/10);
            //更新信息
            member::where(['openid'=>$member_info->openid])->update($arr);
        }else{
            $type = 1;
        }
        $data['type'] = $type;
        if($member_info){
            $member_info['level'] = $member_info['sex']==1?self::LEVEL_MAN[$member_info['level']]:self::LEVEL_WOMAN[$member_info['level']];
            $member_info['crown_num'] = intval($member_info['bonus']/10);
        }
        $data['member_info'] = $member_info;
        fun_respon(1, $data);
    }


    private function getbonus($where){
        $total = member_bonus_record::where($where)->sum('change_bonus');
        return $total;
    }

    /**xxx
     * 添加用户领卡信息
     */
    public function addMember(Request $request)
    {
        try {
            $openid = $request->openid;
            $code = $request->json('code');
            if(!$code) fun_respon(0, '缺少会员信息！');
            $derypt_code = WxSmallClient::derypt($code);
            $data = ['openid'=>$openid, 'code'=>$derypt_code,'derypt_code'=>$code];
            $res = member::insert($data);
            if($res){
                fun_respon(1, '添加成功');
            }
            fun_respon(0, '添加失败');
        } catch (\Exception $ex) {
            fun_respon(0, '系统繁忙，请稍后再试！');
        }
    }

    public function getWeixinMember(){
        $code = '829594183780';
        //$res = WxSmallClient::updateMember($code,'测试增加120','120');
         $res = WxSmallClient::getMember($code);
        var_dump($res);
    }


    /**
     * @param Request $request
     * 添加签到
     */
    public function addSign(Request $request){
        $openid = $request->openid;
        $sign_info = sign_record::where(['openid'=>$openid])->orderBy('id','DESC')->first();
        //判断最后一条的签到记录 如果存在则判断是否为今天 ，不是则签到，如果不存在 直接添加新记录
        $date = date('Y-m-d');
        if($sign_info){
            if($date==date('Y-m-d',strtotime($sign_info['created_at']))){
                fun_respon(0, '今天已经签到过了！');
            }else{
                $data['openid'] = $openid;
                $data['continuous_days'] = $sign_info['continuous_days']+1;
                $data['sign_day'] = $sign_info['sign_day']+1;
                if($data['sign_day']>7) $data['sign_day']=1;
            }
        }else{
            $data['openid'] = $openid;
            $data['continuous_days'] = 1;
            $data['sign_day'] = 1;
        }
        $bonus = 1;
        $res = sign_record::insert($data);
        if($res){
            //添加积分
            $member_info = get_member($openid);
            if($member_info){
                $before_bonus = $member_info['bonus'];
                $change_bonus = $bonus;
                $after_bonus = $before_bonus+$change_bonus;
                $status = 2;
                $type = 1;
                //调用微信的接口加积分
                $record_bonus = sprintf("签到,增加积分%s", $bonus);
                $result = user::where(['openid'=>$openid])->update(['bonus'=>$after_bonus]);
                //if($result->errcode==0){
                add_bonus_record($openid,$before_bonus,$change_bonus,$after_bonus,$status,$type,2);
                //}else{
                    //savelog('wx_bonus', '签到加积分'.$openid.'错误：'.$result->errmsg);
                //}
            }
            fun_respon(1, '签到成功！');
        }
        fun_respon(0, '签到失败！');
    }


    /**
     * @param Request $request
     * 添加签到
     */
    public function addSigns(Request $request){
        $openid = $request->openid;
        $sign_info = sign_record::where(['openid'=>$openid])->orderBy('id','DESC')->first();
        //判断最后一条的签到记录 如果存在则判断是否为今天 ，不是则签到，如果不存在 直接添加新记录
        $date = date('Y-m-d');
        $info_date = date('Y-m-d',strtotime($sign_info['created_at']));
        $day = date('d');
        $year = date('Y');
        $month = date('m');
        $data['year'] = $year;
        $data['month'] = $month;
        $data['sign_day'] = $day;
        $data['openid'] = $openid;
        if($sign_info){
            if($date==$info_date){
                fun_respon(0, '今天已经签到过了！');
            }
            //判断签到的日期是不是每个月的第一天
            if($day=='01'){
                $data['continuous_days'] = 1;
            }else{
                //$today = strtotime($date);
                //时间差大于一天说明不是连续的
                if(($date==date('Y-m-d',strtotime("$info_date+1day")))){
                    $data['continuous_days'] = $sign_info['continuous_days']+1;
                }else{
                    $data['continuous_days'] = 1;
                }
            }
            //增加积分：5分/天 连续签到3天，额外送3分；连续签到7天，额外送5分 , 连续签到15天，额外送10分；连续签到30天，额外送20分
            if($data['continuous_days']>3){
                $bonus = 8;
            }elseif($data['continuous_days']>7){
                $bonus = 10;
            }elseif($data['continuous_days']>15){
                $bonus = 15;
            }elseif($data['continuous_days']>30){
                $bonus = 25;
            }else{
                $bonus = 5;
            }
        }else{
            $data['continuous_days'] = 1;
            $bonus = 5;
        }
        //$bonus = ($data['continuous_days']%7)==0?6:5;
        $res = sign_record::insert($data);
        if($res){
            //添加积分
            $member_info = get_member($openid);
            if($member_info){
                $before_bonus = $member_info['bonus'];
                $change_bonus = $bonus;
                $after_bonus = $before_bonus+$change_bonus;
                $status = 2;
                $type = 1;
                //更新用户的积分和皇冠
                $crown_num = intval($after_bonus/10);
                $res = member::where(['openid'=>$openid])->update(['bonus'=>$after_bonus,'crown_num'=>$crown_num]);

                //调用微信的接口加积分
                $record_bonus = sprintf("签到,增加积分%s", $bonus);
                $result = WxSmallClient::updateMember($member_info['code'],$record_bonus,$change_bonus);
                if($result->errcode==0){
                    add_bonus_record($openid,$before_bonus,$change_bonus,$after_bonus,$status,$type,2);
                }else{
                    savelog('wx_bonus', '签到加积分'.$openid.'错误：'.$result->errmsg);
                }
            }
            fun_respon(1, '签到成功！');
        }
        fun_respon(0, '签到失败！');
    }

    /**
    * @param Request $request
    * 获取签到
    */
    public function getSign(Request $request){
        $openid = $request->openid;
        $sign_info = sign_record::where(['openid'=>$openid])->orderBy('id','DESC')->first();

        $date = date('Y-m-d');
        $info_date = date('Y-m-d',strtotime($sign_info['created_at']));
        if($date==$info_date){
            fun_respon(0, '今天已经签到过了！');
        }else{
            fun_respon(1, '今天还未签到过！');
        }
        //$date = date('Y-m-d');
        if($sign_info){
            fun_respon(1, ['sign_day'=>$sign_info['sign_day']+1,'continuous_days'=>$sign_info['continuous_days']]);
        }else{
            fun_respon(1, ['sign_day'=>1,'continuous_days'=>0]);
        }
    }

    /**
     * @param Request $request
     * 获取签到
     */
    public function getSigns(Request $request){
        $openid = $request->openid;
        $year = date('Y');
        $month = date('m');
        $sign_info = sign_record::where(['openid'=>$openid,'year'=>$year,'month'=>$month])->orderBy('id','ASC')->get(['sign_day','continuous_days'])->toArray();
        //$date = date('Y-m-d');
        if($sign_info){
            //获取数组最后一个值
            $last = end($sign_info);
            $continuous_days = $last['continuous_days']?$last['continuous_days']:0;
            fun_respon(1, ['continuous_days'=>$continuous_days,'days'=>$sign_info]);
        }else{
            fun_respon(1, ['continuous_days'=>0,'days'=>[]]);
        }
    }

}

